/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-05-09
 * Time: 14:28
 */
public class BinarySearchTree {

    //结点
    static class TreeNode {
        public TreeNode left;
        public TreeNode right;
        int val;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root;

    //插入
    public void Insert(int val) {
        TreeNode newNode = new TreeNode(val);
        if (root == null) {
            root = newNode;
            return;
        }
        TreeNode cur = root;
        TreeNode curP = null;
        while (cur != null) {
            if (val > cur.val) {
                curP = cur;
                cur = cur.right;
            } else if (val < cur.val) {
                curP = cur;
                cur = cur.left;
            } else {
                return;
            }
        }
        if (val > curP.val) {
            curP.right = newNode;
        } else {
            curP.left = newNode;
        }
    }


    //查找
    public TreeNode search(int key) {
        TreeNode cur = root;
        while (cur != null) {
            if (key > cur.val) {
                cur = cur.right;
            } else if (key < cur.val) {
                cur = cur.left;
            } else {
                return cur;
            }
        }
        return null;
    }

    //删除
    public void Delete(int val) {
        TreeNode del = root;
        TreeNode prev = null;
        while (del != null) {
            if (val > del.val) {
                prev = del;
                del = del.right;
            } else if (val < del.val) {
                prev = del;
                del = del.left;
            } else {
                break;
            }
        }
        if (del == null) {
            return;//没找到
        }
        DeleteFunc(del, prev);
    }

    private void DeleteFunc(TreeNode del, TreeNode parent) {

    }

}
